#define  _CRT_SECURE_NO_WARNINGS 1
#include "list.h"

SListNode* BuySListNode(SLTDateType x)
{
	SListNode* newnode = (SListNode*)malloc(sizeof(SListNode));
	if (newnode == NULL)
	{
		perror("BuySListNode");
		exit(-1);
	}
	newnode->next = NULL;
	newnode->data = x;
	return newnode;
}
void SListPrint(SListNode* plist)
{
	SListNode* curr = plist;
	while (curr)
	{
		printf("%d->", curr->data);
		curr = curr->next;
	}
	printf("NULL\n");
}
void SListPushBack(SListNode** pplist, SLTDateType x)
{
	assert(pplist);

	SListNode* newnode = BuySListNode(x);
	if (*pplist == NULL)
	{
		*pplist = newnode;
	}
	else
	{
		SListNode* tail = *pplist;
		while (tail->next)
		{
			tail = tail->next;
		}
		tail->next = newnode;
	}
}
void SListPushFront(SListNode** pplist, SLTDateType x)
{
	assert(pplist);

	SListNode* newnode = BuySListNode(x);
	newnode->next = *pplist;
	*pplist = newnode;
}
void SListPopBack(SListNode** pplist)
{
	assert(pplist);
	assert(*pplist);

	if ((*pplist)->next == NULL)
	{
		free(*pplist);
		*pplist = NULL;
	}
	else
	{
		SListNode* curr = *pplist;
		while (curr->next->next)
		{
			curr = curr->next;
		}
		free(curr->next);
		curr->next = NULL;
	}
}
void SListPopFront(SListNode** pplist)
{
	assert(pplist);
	assert(*pplist);

	SListNode* del = *pplist;
	*pplist = (*pplist)->next;
	free(del);
}
SListNode* SListFind(SListNode* plist, SLTDateType x)
{
	SListNode* curr = plist;
	while (curr)
	{
		if (curr->data == x)
			return curr;
		curr = curr->next;
	}
	return NULL;
}
void SListInsert(SListNode** pplist, SListNode* pos, SLTDateType x)
{
	assert(pos);
	assert(pplist);
	if (*pplist == pos)
	{
		SListPushFront(pplist, x);
	}
	else
	{
		SListNode* newnode = BuySListNode(x);
		SListNode* curr = *pplist;
		while (curr->next != pos)
		{
			curr = curr->next;
		}
		curr->next = newnode;
		newnode->next = pos;
	}

}
void SListInsertAfter(SListNode* pos, SLTDateType x)
{
	assert(pos);

	SListNode* newnode = BuySListNode(x);
	newnode->next = pos->next;
	pos->next = newnode;
}
void SListErase(SListNode** pplist, SListNode* pos)
{
	assert(pos);
	assert(*pplist);

	if (*pplist == pos)
	{
		SListPopFront(pplist);
	}
	else
	{
		SListNode* curr = *pplist;
		while (curr->next->next != pos)
		{
			curr = curr->next;
		}
		free(curr->next);
		curr->next = pos;
	}
}
void SListEraseAfter(SListNode* pos)
{
	assert(pos);
	assert(pos->next);

	pos->next = pos->next->next;
	free(pos->next);
}
void SListDestroy(SListNode* plist)
{
	SListNode* curr = plist;
	while (curr)
	{
		SListNode* del = curr;
		curr = curr->next;
		free(del);
	}
}
